package com.ivr.cm.handler.validate.impl;

import java.util.AbstractMap;
import java.util.List;

import org.apache.log4j.Logger;

import com.ivr.cm.cache.Cacheable;
import com.ivr.cm.data.ValidateData;
import com.ivr.cm.handler.validate.ValidateServiceIF;
import com.ivr.cm.vo.ConfigBusinessVo;
import com.ivr.cm.vo.ListWhiteVo;

/**
 * 白名单验证
 * @author liugeng
 * @date 2015-12-18
 *
 */
public class ValidateListWhiteImpl implements ValidateServiceIF {
	private static Logger logger = Logger.getLogger(ValidateListWhiteImpl.class);
	
	private Cacheable configBusinessCache;
	private Cacheable listWhiteCache;

	@SuppressWarnings("unchecked")
	@Override
	public int doProcess(ValidateData validateData) {
		/**获得主叫号码*/
		String mobile =validateData.getBaseData().getCalling();
		/**获得被叫短号码*/
	    String sp_code =validateData.getBaseData().getShort_called();
	    logger.info(String.format("[%s][%s][白名单鉴权]开始", mobile, sp_code));
	    
	    /**获得白名单缓存Map*/
	    AbstractMap<String, List<ListWhiteVo>> listWhiteMap = (AbstractMap<String, List<ListWhiteVo>>) listWhiteCache.getCache();
	    /**从白名单缓存中判断主叫号码是否存在*/
	    List<ListWhiteVo> listWhiteVoList = listWhiteMap.get(mobile);
	    boolean isWhite = false;
	    if(listWhiteVoList != null && listWhiteVoList.size() > 0){
	    	for(ListWhiteVo listWhiteVo :listWhiteVoList){
	    		if(sp_code.equals(listWhiteVo.getSp_code())){
	    			isWhite = true;
		    	}
	    	}
	    }else{
	    	/**不存在白名单中继续验证*/
	    	logger.info(String.format("[%s][%s][白名单鉴权]未通过",mobile, sp_code));
	    	return ValidateChain.VALIDATE_CONTINUE;
	    }
	    
	    if(isWhite){
	    	/**用户存在白名单中无需继续验证 返回可拨打*/
		    AbstractMap<String, ConfigBusinessVo> configBusinessMap = (AbstractMap<String, ConfigBusinessVo>) configBusinessCache.getCache();
		    validateData.setResult(ValidateData.RESULT_VALID);
		    validateData.setVoice("00");
			validateData.setTimeRemain(configBusinessMap.get(sp_code).getOne_shot_limit()*60);
			
			logger.info(String.format("[%s][%s][白名单鉴权]通过", mobile, sp_code));
			
			return ValidateChain.VALIDATE_FINISHED;
	    }else{
	    	/**不存在白名单中继续验证*/
	    	logger.info(String.format("[%s][%s][白名单鉴权]未通过",mobile, sp_code));
	    	return ValidateChain.VALIDATE_CONTINUE;
	    }
	}

	public Cacheable getConfigBusinessCache() {
		return configBusinessCache;
	}
	public void setConfigBusinessCache(Cacheable configBusinessCache) {
		this.configBusinessCache = configBusinessCache;
	}
	public Cacheable getListWhiteCache() {
		return listWhiteCache;
	}
	public void setListWhiteCache(Cacheable listWhiteCache) {
		this.listWhiteCache = listWhiteCache;
	}
}